//
//  YXNetWork+Extension.swift
//  SinaWeiBo
//
//  Created by Vergil on 2017/5/23.
//  Copyright © 2017年 Vergil. All rights reserved.
//

import Foundation

// MARK: - 微博网络请求
extension YXNetWork {
    
    
    /// 加载微博列表数据
    ///
    /// - Parameters:
    ///   - since_id: 若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。(最新的)
    ///   - max_id: 若指定此参数，则返回ID小于或等于max_id的微博，默认为0。(以前的)
    ///   - completion: 完成回调
    func getStatusList(since_id: Int64 = 0, max_id: Int64 = 0, completion: @escaping (_ status: [[String : Any]]? , _ isSuccess: Bool)->()) {
        
        let url = "https://api.weibo.com/2/statuses/home_timeline.json"
        let parameters = ["since_id" : since_id,
                          "max_id" : max_id > 0 ? (max_id - 1) : 0]
        
        netWorkRequest(method: .Get, URLString: url, parameters: parameters) { (response, isSuccess) in
            
            if isSuccess {
                
                let dicResponse = response as? [String : Any]
                let result = dicResponse?["statuses"] as! [[String : Any]]
                completion(result, isSuccess)
                
            } else {
                completion(nil, isSuccess)
            }
            
        }
        
    }
    
    func getUnreadCount(completion: @escaping (_ count: Int)->()) {
        
        let url = "https://api.weibo.com/2/remind/unread_count.json"
        let parameters = ["uid" : userModel.uid!]
        
        netWorkRequest(method: .Get, URLString: url, parameters: parameters) { (response, isSuccess) in
            
            if  isSuccess {
                print(response ?? "")
                let dicResponse = response as! [String : Any]
                let count = dicResponse["status"] as! Int
                completion(count)
            }
            
        }
        
    }
    
}

// MARK: - Aouth授权
extension YXNetWork {
    
    //请求授权
    func loadAccessToken(code: String, completion: @escaping (_ isSuccess: Bool)->()) {
        
        let url = "https://api.weibo.com/oauth2/access_token"
        let parameter = ["client_id" : WBAppKey,
                         "client_secret" : WBAppSecret,
                         "grant_type" : "authorization_code",
                         "code" : code,
                         "redirect_uri" : WBRedirect_uri]
        baseRequest(method: .Post, URLString: url, parameters: parameter) { (response, isSuccess) in
            
            if isSuccess {
                self.userModel.yy_modelSet(with: (response as? [String : Any]) ?? [:])
                
                //保存账号
                self.userModel.saveUserAccount()
                
            }
            
            completion(isSuccess)
            
        }
        
    }
    
}
